<?php
/**
 * @filesource modules/event/controllers/IndexController.php
 * @author Dao Quang Duc
 * @abstract : List of actions in order
 *   - new
 *   - view
 *   - edit
 *   - delete
 *   - search
 */ 
class Tour_IndexController extends Clu_Controller_Action_Hvn
{
	public $m,$c;//, $mPlace, $mArticle;
	public $tl;
	public function init()
	{
		//require_once (APP_PATH.'/modules/place/Model/City.php');
		//require_once (APP_PATH.'/modules/place/Model/District.php');
		//require_once (APP_PATH.'/modules/place/Model/Village.php');
		//require_once (APP_PATH.'/modules/place/Model/Vicinity.php');
		//require_once (APP_PATH.'/modules/category/Model/Category.php');
		//require_once (APP_PATH.'/modules/article/Model/Article.php');
		//require_once (APP_PATH.'/modules/place/Model/Place.php');
		//require_once (APP_PATH.'/modules/user/Model/User.php');
		//require_once (APP_PATH.'/modules/tour/Model/TLeg.php');
		$this->mArticle = new article_Model_Service();
		$this->mPlace = new place_Model_Place();
		$this->mCity = new place_Model_City();
		$this->mDistrict = new place_Model_District();
		$this->m = new Model_Tour();
		//$this->c = new category_Model_Category();
		$this->tl = new Model_TLeg();
		parent::init();
		
	}
	
	public function newAction() 
	{
		//check user permissions here
		$sess = new Zend_Session_Namespace(CLU_NS);
		if (strpos ($sess->userPermissions, 'create tour') === false)
		{
                $this->view->errorMessage = t(68);
                $this->renderToHolder( 'common/error.phtml');
                return;
        }
        
		$this->view->form = new Form_Tour();
        $this->view->form->cluBuild(array ('action' => 'new', 'view' => $this->view, 'userPermissions' => $sess->userPermissions));
     	$this->view->errorMessage = '';
    	$data = $this->_request->getParams();
        if ($this->_request->isPost() && $this->view->form->isValid($_POST)) 
        {
        	$db = $this->db;
	        $db->beginTransaction(); //TODO: to be moved to Model in v2
            try 
            {
            	//get article content
            	$defaultStatus = Zend_Registry::get('configuration')->general->defaultNodeStatus;
            	$data['article_title'] = $data['name'];
            	$data['article_body']  = $data['description'];
            	$data['article_status'] = isset($data['status']) ? $data['status'] : 
            		Zend_Registry::get('configuration')->general->defaultNodeStatus;
            	$data['article_language'] = $data['tour_lang'];
            	$data['article_module'] = "tour";
            	$data['poster_id'] = Zend_Auth::getInstance()->getIdentity()->id;
				$data['poster_name'] = Zend_Auth::getInstance()->getIdentity()->name;
                if (!$this->mArticle->insertRaw($data,false))
                {
                	$this->view->errorMessage = t(503);
                }
                $article_id = $db->lastInsertId();
            	$data['article_id'] = $article_id; 
            	$data['lang'] = $data['tour_lang'];
            	try         	
		    	{
		    	   	$id = $this->m->insertRaw($data,false);
		    	}
		    	catch (Exception $e) 
		    	{
		    		$this->view->errorMessage .= $e->getMessage();
		    		$this->mArticle->deleteByPrimary($article_id, false); //no atomicity
		    	    $this->view->errorMessage .= $e->getMessage() . t(803);
		    	}
                 $db->commit();
            }
            catch (Exception $e)
            {
            	$this->view->errorMessage .= $e->getMessage();
                $db->rollBack();
                $this->view->errorMessage .= t(69);
            }
			 //$this->_forward("success", 'index' , 'event', array('lastInsertId' => $id, 'lang' => 'en' ) );
			//echo $this->view->errorMessage .'abc';
			if (empty($this->view->errorMessage))
			{
				$this->_helper->redirector->gotoUrl($this->view->hvnUrl(array('action'=>'new-tleg', 'module'=>'tour')) . 
															'?tid='.$id.'&leg_number=1');
				return;
			}
        }
        elseif ($this->_request->isPost())
        {
        	$this->view->errorMessage = t(1);
        }
		
		if(!empty($data['type']))
	    	$this->view->type = $data['type'];
	    
	    $loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
		
		$eventSimpleSearchRequest = array(
				'module' => 'event',
				'controller' => 'block',
				'action' => 'simpleSearch',
				'regionId' => 3,
				'boxWeight' => 1,
		);
		$this->addMiniAction($eventSimpleSearchRequest);
		
		$subMenuRequest = array(
				'module' => 'place',
				'controller' => 'block',
				'action' => 'subMenu',
				'regionId' => 3,
				'boxWeight' => 2,
				'page' => 'event',
		);
		$this->addMiniAction($subMenuRequest);
		
		$upcomingEventRequest = array(
                                'module' => 'event',
                                'controller' => 'block',
                                'action' => 'upcomingEvent',
                                'regionId' => 6,
                                'boxWeight' => 1,
                );
		$this->addMiniAction($upcomingEventRequest);
		         
		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest); 
		
        $this->renderToHolder('index/new_tour.phtml', false, null, 4, 1); 
	}
	

	/**
	 * new tour leg action.
	 * 		/en/tour/new-tleg?tid=12&step=1
     */
	public function newTlegAction() 
	{
		//check user permissions here
		$sess = new Zend_Session_Namespace(CLU_NS);
		if (strpos ($sess->userPermissions, 'create tour') === false)
		{
                $this->view->errorMessage = t(68);
                $this->renderToHolder( 'common/error.phtml');
                return;
        }
		//check if tourId is available
        $id = $this->_request->getParam("tid");
        if(!$tour = $this->m->getTourData($id, true, true)) //get tour article & tour leg article
        {
            $this->view->errorMessage = t(804);
			$this->renderToHolder( 'common/error.phtml', false, null, 4, 1);
            return;
        }
        $this->view->tid = $id;
        $this->view->errorMessage = '';
        //if legNumber is not specified, then we get the number of current legs plus 1
        $legNumber = $this->_request->getParam("leg_number") ? $this->_request->getParam("leg_number") : (count($tour['legs']) + 1);
		$this->view->leg_number = $legNumber;
        $this->view->tour = $tour;
        $this->view->form = new Form_TLeg();
        $this->view->form->cluBuild(array ('action' => 'new', 'view' => $this->view, 'userPermissions' => $sess->userPermissions, 'tid' =>$id, 'leg_number' => $legNumber));
     
        if ($this->_request->isPost() && $this->view->form->isValid($_REQUEST)) 
        {
        	$data = $this->_request->getParams();
        	$db = $this->db;
	        $db->beginTransaction();
            try 
            {
            	//get article content
            	$defaultStatus = Zend_Registry::get('configuration')->general->defaultNodeStatus;
            	//$data['article_title'] = $tour['name'] . "leg #" . $legNumber;
            	$data['article_title'] = $data['tleg_name'];
            	$data['article_body']  = $data['description'];
            	$data['article_status'] = isset($data['status']) ? $data['status'] : $defaultStatus;
            	$data['article_module'] = 'tleg';
            	$data['article_language'] = $tour['lang'];
            	$data['poster_id'] =  Zend_Auth::getInstance()->getIdentity()->id;
				
                if ($article_id = $this->mArticle->insertRaw($data,false))
                {
                	/**
                	 * param: belong_to_ids of place, tid of tour
                	 */
                    if(isset($data['belong_to_ids']))
                    	$this->mPlace->relatedTour($data['belong_to_ids'], $data['tid'], null);
                    $data['article_id'] = $article_id;
                	try         	
    		    	{
    		    	   	$this->tl->insertRaw($data,false);
    		    	}
    		    	catch (Exception $e) 
    		    	{
    		    		$this->mArticle->deleteByPrimary($article_id,false); //no need for atomicity
    		    	    $this->view->errorMessage .= $e->getMessage();//t("Could not insert tour");
    		    	}
                     $db->commit();
                }
                else
                {
                	$this->view->errorMessage .= t(503);
                }
            }
            catch (Exception $ex)
            {
                $db->rollBack();
                $this->view->errorMessage .= $ex->getMessage() . t(69);
            }
            
            //forward the 
	    	if (empty($this->view->errorMessage) && $data['is_last_leg'])
	    	{
				$this->_helper->redirector->gotoUrl($this->view->hvnUrl(array('action'=>'success','module'=>'tour')) . 
															'?tid=' . $id);
	    	}
	    	elseif (empty($this->view->errorMessage))
			{
				$nextLeg = $legNumber + 1;
				//forward to the create next leg
				$this->_helper->redirector->gotoUrl($this->view->hvnUrl(array('action'=>'new-tleg','module'=>'tour')) . 
															'?tid='.$id.'&leg_number='.$nextLeg);
			}			 	
        }
        
        $loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
		
		$eventSimpleSearchRequest = array(
				'module' => 'event',
				'controller' => 'block',
				'action' => 'simpleSearch',
				'regionId' => 3,
				'boxWeight' => 1,
		);
		$this->addMiniAction($eventSimpleSearchRequest);
		
		$subMenuRequest = array(
				'module' => 'place',
				'controller' => 'block',
				'action' => 'subMenu',
				'regionId' => 3,
				'boxWeight' => 2,
				'page' => 'event',
		);
		$this->addMiniAction($subMenuRequest);
		
		$upcomingEventRequest = array(
                                'module' => 'event',
                                'controller' => 'block',
                                'action' => 'upcomingEvent',
                                'regionId' => 6,
                                'boxWeight' => 1,
                );
		$this->addMiniAction($upcomingEventRequest);
		         
		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest); 
		
        $this->renderToHolder('index/new_tleg.phtml', false, null, 4, 1); 
    	return;
	}
	
		
	public function viewAction() 
	{
		$id = $this->_request->getParam("id");
    	if(!$tour = $this->m->getTourData($id, true, true)) //get tour article & tour leg article
        {
            $this->view->errorMessage = t(805);
            $this->renderToHolder('common/error.phtml');
            return;
        }
        $a = $this->mArticle->getArticleData($tour['article_id']);
        $tour['article'] = $a;
        $aTleg = $this->tl->getLegData($id, true);
        $tlegData = $this->tl->getLegsByTourId($id);
        if(isset($tlegData))
        {
	        foreach($tlegData as $aid)
	        	$lidArray[] = $aid['leg']['article_id'];
	    	$aTleg = $this->tl->getLegData($lidArray, true);
	   		$this->view->aTlegData = $aTleg;
        }        	
        $this->view->tour = $tour;
        
		$sess = new Zend_Session_Namespace(CLU_NS);
        $auth = Zend_Auth::getInstance();
        $this->view->edit_allowed = false;
        if (strpos ($sess->userPermissions, 'update tour'))//tour admin
        	$this->view->edit_allowed = true;
		elseif ($auth->hasIdentity())
		{
            $uIdentity = $auth->getIdentity();
    		if (isset($uIdentity->id) == $tour['poster_id'] && strpos ($sess->userPermissions, 'update own tour'))
    		{
    			$this->view->edit_allowed = true;
    		}
        }

        $this->renderToHolder('index/view.phtml', false, null, 4, 1);

        $loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
		
		$tourSimpleSearchRequest = array(
				'module' => 'tour',
				'controller' => 'block',
				'action' => 'simpleSearch',
				'regionId' => 3,
				'boxWeight' => 1,
		);
		$this->addMiniAction($tourSimpleSearchRequest);
		
		$subMenuRequest = array(
				'module' => 'place',
				'controller' => 'block',
				'action' => 'subMenu',
				'regionId' => 3,
				'boxWeight' => 2,
				'page' => 'tour',
		);
		$this->addMiniAction($subMenuRequest);
		
//		$listInBoundRequest = array(
//					'module' => 'tour',
//					'controller' => 'block',
//					'action' => 'listInBound',
//					'regionId' => 4,
//					'boxWeight' => 3,
//			);
//		$this->addMiniAction($listInBoundRequest);
//
//		$listOutBoundRequest = array(
//					'module' => 'tour',
//					'controller' => 'block',
//					'action' => 'listOutBound',
//					'regionId' => 4,
//					'boxWeight' => 4,
//			);
//		$this->addMiniAction($listOutBoundRequest);
		
        $commentRequest = array(
        						'module' => 'comment',
        						'controller' => 'block',
        						'action' => 'moduleComment',
        						'regionId' => 4,
        						'boxWeight' => 8,
        						'id' => $id,
        						'comments_per_page' => 10,
        						'page_number' => 1,
        						'parent_content_type' => 'tour' 
        						);
        $this->addMiniAction($commentRequest);	
	    
	    $tourRequest = array(
                                'module' => 'tour',
                                'controller' => 'block',
                                'action' => 'hotTourList',
                                'regionId' => 6,
                                'boxWeight' => 2,
                );
		$this->addMiniAction($tourRequest);
		
        //block gallery 
		$galleryRequest = array(
				'module' => 'file',
				'controller' => 'block',
				'action' => 'imageList',
				'regionId' => 6,
				'boxWeight' => 1,
				'poster_id' => $tour['poster_id'],
				'c' => 'tour',
				't' => 'image',
				'uid' => $tour['poster_id'],
				'id'  => $tour['id'],
				'galleryId' => 'gallery-tour-' . $tour['id'],
				
		);
		$this->addMiniAction($galleryRequest); 
     	
     	$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
		   
	}
	
	public function editAction()
	{
		$sess = new Zend_Session_Namespace(CLU_NS);
    	$id = $this->_request->getParam("id");
    	if(!$tour = $this->m->getTourData($id, true, false)) //get tour article & tour leg article
        {              
            $this->view->errorMessage = t(209);
            $this->renderToHolder('common/error.phtml');
            return;
        }
		//check for permission here
		//check rights
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity())
		{
		 	$this->view->errorMessage = t(402);
            $this->renderToHolder('common/error.phtml');
            return;
		}

		$uIdentity = $auth->getIdentity();
		$sess = new Zend_Session_Namespace(CLU_NS);
		//if not admin
		// or not owner
		if ((isset($uIdentity->id) != $tour['poster_id'] && strpos ($sess->userPermissions, 'update tour') === false) ||
			(isset($uIdentity->id) == $tour['poster_id'] && strpos ($sess->userPermissions, 'update own tour') === false))
		{
		 	$this->view->errorMessage = t(806);
            $this->renderToHolder('common/error.phtml');
            return;
		}        
        
        //everything's fine. Continue editing
        $form = new Form_Tour();
        $form->cluBuild(array ('action' => 'edit', 'view' => $this->view, 'userPermissions' => $sess->userPermissions,'id' => $id));
        //populate the data  
		if($this->_request->isGet())
		{
			//$data = $this->m->transformToFormArray($tour);
            $form->populate($this->m->transformToFormArray($tour));
		}
			
        else if ($form->isValid($_POST))
        {	
			$data = $this->_request->getParams();
        	$articleData = array();
            $articleData['article_title'] = $data['name'];
            $articleData['article_body'] = $data['description'];
            $article_id = $tour['article']['article_id'];
//            $articleData['article_language'] = $data['tour_lang'];
            if (!($this->mArticle->saveRaw(null, $articleData, $article_id,false))) //no validation
            	$this->view->errorMessage .= t(507);
            if ($this->m->saveRaw(null, $data, $id, false)) //don't pass tour obj because $tour is getTourData, not findByPrimary
            {
                $this->view->successMessage = t(807);
            }
            else 
                $this->view->errorMessage = t(808);
        }
        else 
        	$this->view->errorMessage = t(71);
        	
        $this->view->form = $form;
		//$this->view->article_id = $e['article_id']; //for form submission
        $this->view->id = $id;
        $this->view->mode = 'edit';
        
        $loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
		
        $tourSimpleSearchRequest = array(
				'module' => 'tour',
				'controller' => 'block',
				'action' => 'simpleSearch',
				'regionId' => 3,
				'boxWeight' => 1,
		);
		$this->addMiniAction($tourSimpleSearchRequest);
		
        $subMenuRequest = array(
				'module' => 'place',
				'controller' => 'block',
				'action' => 'subMenu',
				'regionId' => 3,
				'boxWeight' => 2,
				'page' => 'tour',
		);
		$this->addMiniAction($subMenuRequest);
		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
		
		$tourRequest = array(
                                'module' => 'tour',
                                'controller' => 'block',
                                'action' => 'hotTourList',
                                'regionId' => 6,
                                'boxWeight' => 1,
                );
		$this->addMiniAction($tourRequest);
		
        $this->renderToHolder('index/new_tour.phtml', false, null, 4, 1);    
	}

	public function editTlegAction()
	{
		$sess = new Zend_Session_Namespace(CLU_NS);
    	$id = $this->_request->getParam("id");
    	
    	if(!$leg = $this->tl->getLegData($id, true)) //get leg article
        {              
            $this->view->errorMessage = t(209);
            $this->renderToHolder('common/error.phtml');
            return;
        }
        
        //tour authentication
        if(!$tour = $this->m->findByPrimary($leg['tid'])) //get tour article & tour leg article
        {              
            $this->view->errorMessage = t(805);
            $this->renderToHolder('common/error.phtml');
            return;
        }
        
		//check for permission here, check rights
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity())
		{
		 	$this->view->errorMessage = t(806);
            $this->renderToHolder('common/error.phtml');
            return;
		}

		$uIdentity = $auth->getIdentity();
		$sess = new Zend_Session_Namespace(CLU_NS);
		//if not admin or not owner
		if ((isset($uIdentity->id) != $tour['poster_id'] && strpos ($sess->userPermissions, 'update tour') === false) ||
			(isset($uIdentity->id) == $tour['poster_id'] && strpos ($sess->userPermissions, 'update own tour') === false))
		{
		 	$this->view->errorMessage = t(809);
            $this->renderToHolder('common/error.phtml');
            return;
		}        
        
        //everything's fine. Continue editing
        $form = new Form_TLeg();
        $form->cluBuild(array ('action' => 'edit', 'view' => $this->view, 'userPermissions' => $sess->userPermissions,'id' => $id));
        $formName = "Edit_Tleg";        
        //populate the data
		if($this->_request->isGet())
	        $form->populateForm($formName, $leg);
			
        else if ($this->_request->isPost() && $form->isValid($_POST))
        {	
			$data = $this->_request->getParams();
        	$articleData = array();
            $articleData['article_title'] = $data['tleg_name'];
            $articleData['article_body'] = $data['description'];
            $article_id = $leg['article']['article_id'];
            if (!($this->mArticle->saveRaw(null, $articleData, $article_id, false))) //no validation
            	$this->view->errorMessage .= t(507);
            
	        $fData = unserialize($leg['metadata']);
            if($data['belong_to_ids'] != $fData['arrival_place_id'])
            {
            	$this->mPlace->relatedTour($data['belong_to_ids'], $leg['tid'], $fData['arrival_place_id']);
            }
            
            if ($this->tl->saveRaw(null, $data, $id, false)) //don't pass tour obj because $tour is getTourData, not findByPrimary
            {
                $this->view->successMessage = t(807);
            }
            else 
                $this->view->errorMessage .= t(808);
        }
        else 
        	$this->view->errorMessage = t(71);
        
        $e = $this->tl->findByPrimary($id);
        $fData = unserialize($e->metadata);
        if(isset($fData['arrival_place_id']))
        {
            $this->view->departurePlaceid = $fData['departure_place_id'];
            $this->view->departurePlaceName = $fData['departure_place_name'];
            $this->view->arrivalPlaceid = $fData['arrival_place_id'];
            $this->view->arrivalPlaceName = $fData['arrival_place_name'];
        }
	        	
        $this->view->form = $form;
        $this->view->id = $id;
        $this->view->tid = $leg['tid'];
        $this->view->mode = 'edit-tleg'; 
        
        $loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
		
        $tourSimpleSearchRequest = array(
				'module' => 'tour',
				'controller' => 'block',
				'action' => 'simpleSearch',
				'regionId' => 3,
				'boxWeight' => 1,
		);
		$this->addMiniAction($tourSimpleSearchRequest);
		
        $subMenuRequest = array(
				'module' => 'place',
				'controller' => 'block',
				'action' => 'subMenu',
				'regionId' => 3,
				'boxWeight' => 2,
				'page' => 'tour',
		);
		$this->addMiniAction($subMenuRequest);
		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
		
		$tourRequest = array(
                                'module' => 'tour',
                                'controller' => 'block',
                                'action' => 'hotTourList',
                                'regionId' => 6,
                                'boxWeight' => 1,
                );
		$this->addMiniAction($tourRequest);
		
        $this->renderToHolder('index/new_tleg.phtml', false, null, 4, 1);    
	}
	
	public function searchAction()
    {
    	$data = $this->_request->getParams();
      	$sess = new Zend_Session_Namespace(CLU_NS);
    	
		if (strpos($sess->userPermissions, "administer tour"))
			$cluSearchMode = "fullAdminSearch";
	    else
			$cluSearchMode = "fullSearch";
    	
    	$form = new Form_TourSearch();
      	$form->cluBuild(array('cluSearchMode' => $cluSearchMode, 'view' => $this->view, 'action' => 'search'));
        $this->view->form = $form; 
		if($this->_request->isPost() && $form->isValid($_POST))
		{
		
			if(isset($data['quick_time_range_mode']))
			{
				switch($data['quick_time_range_mode'])
				{
					case 1:
					{
						$data['departure_date'] = date("d/m/Y",time());
						$data[ 'return_date'] = date("d/m/Y",time() + 604800); // 604800s = 7days
						break;
					}
					
					case 2:
					{
						$data['departure_date'] = date("d/m/Y",time());
						$data[ 'return_date'] = date("d/m/Y",time() + 2592000); // 2592000s = 30days
						break;
					}
					
					case 3:
					{
						$data['departure_date'] = date("d/m/Y",time());
						$data[ 'return_date'] = date("d/m/Y",time() + 7776000); // 7776000s = 90days
						break;
					}
				}
				$data['quick_time_range_mode'] = NULL;
			}
			
			if(!isset($data['tours_per_page']))
				$data['tours_per_page'] = 10;
			if(!isset($data['page']))
				$data['page'] = 1;
				
	    	if($paginator = $this->m->search($data))
    		{
    			$paginator = $this->generatePaginator($paginator, 1, $data['tours_per_page'], 3, 'Jumping');
                $form->populate($data);  
    			
    			//cache in $_SESSION
               	$sessPaginator = new Zend_Session_Namespace("tour_paginator");
                $sessPaginator->tour_admin = array("search_params" => $data); 
        	}
		}
        else if(!empty($data['page']) && $data['page'] != null){
			$sessPaginator = new Zend_Session_Namespace("tour_paginator");
        	$data = $sessPaginator->tour_admin;
           	if(isset($data))
           	{
               $select = $this->m->search($data['search_params']);
               $paginator = $this->generatePaginator($select, $this->_getParam('page'), $data['search_params']['tours_per_page'], 3, 'Jumping');
               $form->populate($data['search_params']);//populate form
           	}
        }

        if(isset($paginator))
       	{                
            $this->view->paginator = $paginator;
            $tourList = $this->m->transformToViewData($paginator->getCurrentItems());
    		$this->view->tList = $tourList;//list of found events
    		
    		//get articles
			$articleList = array();
			$mArticle = new article_Model_Service();
			foreach ($this->view->tList as $t)
			{
				$articleList[$t['id']] = $mArticle->getArticleData($t['article_id']);
			}
			$this->view->aList = $articleList;
			$p = $this->_request->getParam('page');
			$pageNum  = !empty($p) ? $p : 1; 
			$perPage = isset($data['tours_per_page']) ? $data['tours_per_page']:  $data['search_params']['tours_per_page'];
			$this->view->startIndex = $perPage * ($pageNum - 1);
			$this->view->numberOfItems = $paginator->getTotalItemCount();
			$this->view->perPage = $perPage;
			$this->view->pageNum = $pageNum;
			$this->view->numberOfPages = ceil($this->view->numberOfItems/$this->view->perPage);
    		if (strpos($sess->userPermissions, "administer everything"))
				$this->renderToHolder('index/list_admin.phtml',false, null, 4,2); 
			else
            	$this->renderToHolder('index/list.phtml',false, null, 4,3); 
       	}
        $this->renderToHolder('index/'.$cluSearchMode . '.phtml', false, null, 4,1);
        
        $loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
		
        $tourSimpleSearchRequest = array(
				'module' => 'tour',
				'controller' => 'block',
				'action' => 'simpleSearch',
				'regionId' => 3,
				'boxWeight' => 1,
		);
		$this->addMiniAction($tourSimpleSearchRequest);
		
        $subMenuRequest = array(
				'module' => 'place',
				'controller' => 'block',
				'action' => 'subMenu',
				'regionId' => 3,
				'boxWeight' => 2,
				'page' => 'tour',
		);
		$this->addMiniAction($subMenuRequest);
		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
		
		$tourRequest = array(
                                'module' => 'tour',
                                'controller' => 'block',
                                'action' => 'hotTourList',
                                'regionId' => 6,
                                'boxWeight' => 1,
                );
		$this->addMiniAction($tourRequest);
		
		/*
        $topTourListRequest = array(
				'module' => 'tour',
				'controller' => 'block',
				'action' => 'topTourList',
				'regionId' => 5,
				'boxWeight' => 0,
		);
		$this->addMiniAction($topTourListRequest);
		*/
    }
    
	public function generatePaginator($select, $pageNumber, $itemsPerPage, $pageRange, $style)
    {
        $paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select));
        $paginator->setItemCountPerPage($itemsPerPage);
        $paginator->setCurrentPageNumber($pageNumber);
        $paginator->setPageRange($pageRange);
        Zend_Paginator::setDefaultScrollingStyle($style);
        return $paginator;
    }

	public function successAction()
    {
         $this->view->tid =  $this->_request->getParam("tid");
         $this->renderToHolder( 'common/success.phtml');  
    }
    
    /*
    public function populateTourForm(&$form, $data)
    {
        //Populate district options
        if(isset($data['arrival_city_id']))
        { 
        	$cityId = $data['arrival_city_id'];
	    	if ($cityId != 0)
		    {
			    $districts = $this->mDistrict->getDistricts($cityId);
				foreach ($districts as $d) 
	          	    $form->district_id->addMultiOption($d['district_id'], $d['district_name']);
		    }
        }
        if(isset($data['departure_city_id']))
        {
        	$cityId = $data['departure_city_id'];
	    	if ($cityId != 0)
		    {
			    $districts = $this->mDistrict->getDistricts($cityId);
				foreach ($districts as $d) 
	          	    $form->departure_district_id->addMultiOption($d['district_id'], $d['district_name']);
		    }
        }
    }
    */
    
    public function galleryAction()
    {
        $tourId = $this->_request->getParam("id");
        $p = $this->m->findByPrimary($tourId, true);
        $auth = Zend_Auth::getInstance();
       	$uIdentity = $auth->getIdentity();
        if (!$p)
        {
        	$this->view->errorMessage .= t(213);
            $this->renderToHolder( 'common/error.phtml');
            return;
        }
        $this->view->id = $tourId;
        if(!empty($uIdentity))
        	$this->view->uid = isset($uIdentity->id);
        
        $loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
		
        $tourSimpleSearchRequest = array(
				'module' => 'tour',
				'controller' => 'block',
				'action' => 'simpleSearch',
				'regionId' => 3,
				'boxWeight' => 1,
		);
		$this->addMiniAction($tourSimpleSearchRequest);
		
        $subMenuRequest = array(
				'module' => 'place',
				'controller' => 'block',
				'action' => 'subMenu',
				'regionId' => 3,
				'boxWeight' => 2,
				'page' => 'tour',
		);
		$this->addMiniAction($subMenuRequest);
		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
		
		$tourRequest = array(
                                'module' => 'tour',
                                'controller' => 'block',
                                'action' => 'hotTourList',
                                'regionId' => 6,
                                'boxWeight' => 1,
                );
		$this->addMiniAction($tourRequest);
		
        $this->renderToHolder( 'index/gallery.phtml', false, null, 4, 1);                 
    }
    
    public function listTlegAction()
    {
    	$tourId = $this->_request->getParam("id");
    	$sql = "SELECT * FROM tlegs tl WHERE tl.tid = ".$tourId;
    	$results = $this->db->query($sql);
    	$listTlegs = $results->fetchAll();
    	
    	$this->view->listTleg = $listTlegs;
    	//get Article
    	$articleList = array();
		$mArticle = new article_Model_Service();
		foreach ($this->view->listTleg as $t)
		{
			$articleList[$t['id']] = $mArticle->getArticleData($t['article_id']);
		}
		$this->view->aList = $articleList;
			
    	$this->view->id = $tourId;
    	
    	$loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
		
        $tourSimpleSearchRequest = array(
				'module' => 'tour',
				'controller' => 'block',
				'action' => 'simpleSearch',
				'regionId' => 3,
				'boxWeight' => 1,
		);
		$this->addMiniAction($tourSimpleSearchRequest);
		
        $subMenuRequest = array(
				'module' => 'place',
				'controller' => 'block',
				'action' => 'subMenu',
				'regionId' => 3,
				'boxWeight' => 2,
				'page' => 'tour',
		);
		$this->addMiniAction($subMenuRequest);
		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
		
		$tourRequest = array(
                                'module' => 'tour',
                                'controller' => 'block',
                                'action' => 'hotTourList',
                                'regionId' => 6,
                                'boxWeight' => 1,
                );
		$this->addMiniAction($tourRequest);
		
       	$this->renderToHolder('index/listTleg.phtml', false, null, 4, 1);
    }
    
    public function homeAction()
	{
		$sess = new Zend_Session_Namespace(CLU_NS);
		
		$loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
		
		$tourSimpleSearchRequest = array(
				'module' => 'tour',
				'controller' => 'block',
				'action' => 'simpleSearch',
				'regionId' => 3,
				'boxWeight' => 1,
		);
		$this->addMiniAction($tourSimpleSearchRequest);
		
		$subMenuRequest = array(
				'module' => 'place',
				'controller' => 'block',
				'action' => 'subMenu',
				'regionId' => 3,
				'boxWeight' => 2,
				'page' => 'tour',
		);
		$this->addMiniAction($subMenuRequest);
		
		$simpleSearchRequest = array(
                        'module' => 'tour',
                        'controller' => 'block',
                        'action' => 'listCompany',
                        'regionId' => 4,
                        'boxWeight' => 1,
						'page' => 'home'
        );
		$this->addMiniAction($simpleSearchRequest);

		$listInBoundRequest = array(
					'module' => 'tour',
					'controller' => 'block',
					'action' => 'listInBound',
					'regionId' => 4,
					'boxWeight' => 3,
			);
		$this->addMiniAction($listInBoundRequest);

		$listOutBoundRequest = array(
					'module' => 'tour',
					'controller' => 'block',
					'action' => 'listOutBound',
					'regionId' => 4,
					'boxWeight' => 4,
			);
		$this->addMiniAction($listOutBoundRequest);
		
		$saleOffRequest = array(
					'module' => 'tour',
					'controller' => 'block',
					'action' => 'saleOff',
					'regionId' => 4,
					'boxWeight' => 5,
			);
		$this->addMiniAction($saleOffRequest);
		
		$advisoryRequest = array(
					'module' => 'tour',
					'controller' => 'block',
					'action' => 'advisory',
					'regionId' => 4,
					'boxWeight' => 7,
			);
		$this->addMiniAction($advisoryRequest);
		
//		$eventRequest = array(
//                                'module' => 'event',
//                                'controller' => 'block',
//                                'action' => 'featuredList',
//                                'regionId' => 4,
//                                'boxWeight' => 5,
//								'page' => 'home'
//                );
//		$this->addMiniAction($eventRequest);
		
		
//		$placeRequest = array(
//                                'module' => 'place',
//                                'controller' => 'block',
//                                'action' => 'featuredList',
//                                'regionId' => 4,
//                                'boxWeight' => 2,
//								'page' => 'home'
//                );
//		$this->addMiniAction($placeRequest);
		
		$tourRequest = array(
                                'module' => 'tour',
                                'controller' => 'block',
                                'action' => 'hotTourList',
                                'regionId' => 6,
                                'boxWeight' => 1,
                );
		$this->addMiniAction($tourRequest);
		         

        //todo: just sample to test layout. to be removed
//		$placeBrowseByCategoriesRequest = array(
//				'module' => 'place',
//				'controller' => 'block',
//				'action' => 'browseByCategory',
//				'regionId' => 5,
//				'boxWeight' => 0,
//		);
//		$this->addMiniAction($placeBrowseByCategoriesRequest);
		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
		
//		$listNatureRequest = array(
//					'module' => 'place',
//					'controller' => 'block',
//					'action' => 'listNature',
//					'regionId' => 4,
//					'boxWeight' => 5,
//					'rtype' => 18,
//					'page' => 'place',
//			);
//		$this->addMiniAction($listNatureRequest);
		
//		$tabMenuRequest = array(
//                                'module' => 'place',
//                                'controller' => 'block',
//                                'action' => 'tabMenu',
//                                'regionId' => 4,
//                                'boxWeight' => 3,
//                );
//		$this->addMiniAction($tabMenuRequest);
		
//		$listRestaurantRequest = array(
//					'module' => 'place',
//					'controller' => 'block',
//					'action' => 'listRestaurant',
//					'regionId' => 4,
//					'boxWeight' => 4,
//					'category_rtype' => 20,
//					'type' => 45,
//			);
//		$this->addMiniAction($listRestaurantRequest);
	}
}
?>
